package com.ssy.lingxi.search.common.utils;

import java.util.List;

/**
 * list数组分页工具类
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/8/13
 */
public class ListPageUtil {
    /**
     * 分页查询
     * @param list
     * @param pageNum 页码
     * @param pageSize 每页多少条数据
     * @return
     */
    public static <T> List page(List<T> list, Integer pageNum,Integer pageSize) {
        if (list == null || list.size() == 0) {
            return null;
        }

        Integer count = list.size(); // 记录总数
        int pageCount; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        int fromIndex; // 开始索引
        int toIndex; // 结束索引

        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }

        if (fromIndex + 1 > list.size()) {
            return null;
        }

        return list.subList(fromIndex, toIndex);
    }
}
